using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 恐惧Buff - 使目标远离施法���
/// </summary>
public class FearBuff : BuffBase
{
    private Vector3 m_FearDirection;
    private float m_FearSpeed;
    private bool m_IsFleeing;

    public FearBuff(BuffData buffData, Entity caster, Entity target) : base(buffData, caster, target)
    {
        if (buffData is FearData fearData)
        {
            m_FearSpeed = fearData.FleeSpeed;
        }
        else
        {
            m_FearSpeed = 5.0f; // 默认逃跑速度
        }
        
        // 计算恐惧方向（远离施法者）
        if (Caster != null)
        {
            m_FearDirection = (Target.transform.position - Caster.transform.position).normalized;
        }
        else
        {
            m_FearDirection = Vector3.right; // 默认向右逃跑
        }
    }

    protected override void OnStart()
    {
        base.OnStart();
        
        m_IsFleeing = true;
        
        // 播放恐惧特效
        if (BuffData.Effect != null)
        {
            var effect = GameObject.Instantiate(BuffData.Effect, Target.transform);
            effect.transform.localPosition = Vector3.zero;
        }
        
        // 设置动画状���
        if (Target.Animator != null)
        {
            Target.Animator.SetBool("fear", true);
        }
        
        Logger.Log($"{Target.name} 感到恐惧，开始逃跑");
    }

    protected override void OnTick(float dt)
    {
        base.OnTick(dt);
        
        if (m_IsFleeing && Target.MoveComponent != null)
        {
            // 执行逃跑移动
            Vector3 currentPos = Target.transform.position;
            Vector3 newPos = currentPos + m_FearDirection * m_FearSpeed * dt;
            Target.transform.position = newPos;
        }
    }

    protected override void OnFinish()
    {
        base.OnFinish();
        m_IsFleeing = false;
        Logger.Log($"{Target.name} 恐惧效果结束");
    }

    protected override void OnRemove()
    {
        base.OnRemove();
        
        m_IsFleeing = false;
        
        // 恢复动画状���
        if (Target.Animator != null)
        {
            Target.Animator.SetBool("fear", false);
        }
        
        // 清理特效
        var effects = Target.GetComponentsInChildren<ParticleSystem>();
        foreach (var effect in effects)
        {
            if (effect.name.Contains("Fear"))
            {
                GameObject.Destroy(effect.gameObject);
            }
        }
    }

    public override bool IsCanMerge()
    {
        return false; // 恐惧效果不能叠加，只能刷新持续时���
    }
}
